import { createRouter, createWebHistory } from 'vue-router'
import { FetchUser } from "@/service/getData"
const { VerifyToken } = FetchUser();

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/greenhouse',
      name: 'greenhouse',
      component: () => import('../views/greenhouse.vue'),meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
    }
  ],
})
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');

  if (to.meta.requiresAuth) {
    if (!token) {
      next({ path: '/login' });
    } else {
      VerifyToken(token)
          .then(response => {
            if (response.code == 1){
              next({ path: '/login' });
            }else{
              next();
            }
          }).catch(error => {
        console.error('验证 token 时出错:', error);
      });
    }
  } else {
    next();
  }
});
export default router
